package com.mco.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author ：liao.wei
 * @date ：2023/9/20 20:30
 * @package : com.mco.service
 */
@Service
@Slf4j
public class HyperLogLogService {
	
	@Resource
	private RedisTemplate redisTemplate;
	
	/**
	 * 模拟用户点击淘宝首页，每个用户不同ip
	 */
//	@PostConstruct
	public void initIP() {
		new Thread(() -> {
			String ip = null;
			for (int i = 0; i < 200; i++) {
				Random random = new Random();
				ip = random.nextInt(256) + "." + random.nextInt(256)
						+ "." + random.nextInt(256) + "." + random.nextInt(256);
				Long hll = redisTemplate.opsForHyperLogLog().add("hll", ip);
				log.info("IP={},访问首页的次数={}", ip, hll);
				try {
					TimeUnit.SECONDS.sleep(2);
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		},"t1").start();
	}
	
	public  Long uv(){
		return redisTemplate.opsForHyperLogLog().size("hll");
	}
}
